<?php

namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;
    public $table = 'users';
    public $timestamps = false;
    protected $fillable = [
        'account', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'token',
    ];

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    /*
     * TODO::查询账号是否存在，并返回数量
     * */
    public static function accountExist(string $account,$excludeId = 0){
        $count = self::where('account',$account)
            ->where('id', '!=', $excludeId)
            ->count();
        return $count;
    }

    public static function getUserByAccount(string $account){
        $info = self::where(['account'=>$account])
            ->select([
                'id',
                'account',
                'name',
                'mobile',
                'status'
            ])->first();
        if($info){
            return $info;
        }else{
            return false;
        }
    }

    public static function getUserById(int $id){
        $info = self::where(['id'=>$id])->first();
        if($info){
            return $info;
        }else{
            return false;
        }
    }

    public static function usable($account){
        $userInfo = self::getUserByAccount($account);
        if($userInfo){
            if($userInfo->status == 0){
                /*状态停用*/
                return [
                    'code'=>500,
                    'msg'=>'账号已停用'
                ];
            } else {
                return [
                    'code'=>200,
                    'msg'=>'账号正常，可以登陆'
                ];
            }
        }else{
            return [
                'code'=>500,
                'msg'=>'账号或密码错误'
            ];
        }
    }

    public static function roles($user_id){
        $roles = DB::table('roles')
            ->where('user_id', '=', $user_id)
            ->select('role_name')
            ->get()
            ->toArray();
        $roles = array_column($roles,'role_name');
        return $roles;
    }
}
